//
//  KKCountDownButton.m
//  YanzhouCloud
//
//  Created by Cocoa on 2019/7/4.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "KKCountDownButton.h"

@interface KKCountDownButton ()
@property (nonatomic, strong) NSTimer * timer;

//记录开始的时间，app进入后台前台使用
@property (nonatomic, assign) NSInteger startSecond;
@end

@implementation KKCountDownButton
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [self setup];
}
- (void)setup {
    self.currentCount = self.count;
}

- (void)startTimer{
    self.enabled = NO;
    
    //记录点击开始的时间
    self.startSecond = [[NSDate date] timeIntervalSince1970];
    self.currentCount = self.count;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextCount) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)endTimer {
    self.startSecond = 0;
    if (self.timer.isValid) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)nextCount{
    if (self.currentCount > 0) {
        if(self.CountDownBlock){
            self.CountDownBlock(self.currentCount);
        }else{
            [self setTitle:[NSString stringWithFormat:@"%lds",(long)self.currentCount] forState:UIControlStateNormal];
        }
        self.currentCount --;
    }else{
        [self endTimer];
        self.enabled = YES;
        if(self.CountDownBlock){
            self.CountDownBlock(self.currentCount);
        }else{
            [self setTitle:@"重新发送" forState:UIControlStateNormal];
        }
        self.currentCount = self.count;
    }
}

@end
